<?php
namespace app\index\controller;
use app\index\model\Ticketlogs; 
use think\Controller;

use think\Db;
/**
 * 支付接口
 * @author 
 * @version 2017-02-09 17:00:00
 */
class PaymentController extends Controller {
	//申请普通会员企业会员
	public function mem_pay(){
	header('Access-Control-Allow-Origin:*');
		if (request()->isAjax()) {
			$config =get_config('ticket_config');
			$type=input("type");//1普通会员2企业会员
			if($type==1){
				$price=$config['m_balance'];
				$tj_yj=$config['tj1'];
				$tj_yj2=$config['tj2'];
				$pt_yj=$config['pt_yj'];
				$city_yj=$config['city_yj'];
				
			}elseif($type==2){
				$price=$config['qy_balance'];
				$tj_yj=$config['qy_tj1'];
				$tj_yj2=$config['qy_tj2'];
				$pt_yj=$config['pt_yj2'];
				$city_yj=$config['city_qyyj'];
			}
			$sn=order_create_no();
			$user=session('user_info');
			$openid=$user['open_id'];
			$this->add_log($sn,$price,$type,$user['pid1'],$user['pt_id'],$user['pid2'],$tj_yj,$tj_yj2,$pt_yj,$user['city_id'],$city_yj);
			import("payment.wxpay.WxPayApi");
			import("payment.wxpay.JsApiPay");
			$tools = new \JsApiPay();
			$input = new \WxPayUnifiedOrder();
			$input->SetBody('杨梅色彩创客平台');
			$input->SetAttach('杨梅色彩创客平台');
			$input->SetOut_trade_no($sn);
			$input->SetTotal_fee($price*100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'index/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openid);
		
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo $jsApiParameters;
			exit;
		} else {
			return $this->fetch();
		}
	}
	//收款码付款
	public function sk_pay(){
	header('Access-Control-Allow-Origin:*');
		if (request()->isAjax()) {
			$price=input('money');
			$sn=order_create_no();
			$openid=session("openid");
			$tj_id=input('fromuid');
			$tj_user=db('member')->where('id',$tj_id)->field("pid1,pid2,pt_id,city_id")->find();
			$config =get_config('ticket_config');
			$pt_id=$tj_user['pt_id'];//合伙人
			$tj_id2=$tj_user['pid1'];//二级推荐会员
			$city_id=$tj_user['city_id'];
			$tj_yj=$config['tj1'];
			$tj_yj2=$config['tj2'];
			$pt_yj=$config['pt_yj'];
			$city_yj=$config['city_yj'];
			if(!session('user_info')){
				$this->add_user($openid, $tj_id, $pt_id,$tj_id2,$city_id);
			}
			$this->add_log($sn,$price,1,$tj_id,$pt_id,$tj_id2,$tj_yj,$tj_yj2,$pt_yj,$city_id,$city_yj);
			import("payment.wxpay.WxPayApi");
			import("payment.wxpay.JsApiPay");
			$tools = new \JsApiPay();
			$input = new \WxPayUnifiedOrder();
			$input->SetBody('杨梅色彩轻创平台');
			$input->SetAttach('杨梅色彩创客开通');
			$input->SetOut_trade_no($sn);
			$input->SetTotal_fee($price*100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'index/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openid);
		
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo $jsApiParameters;
			exit;
		} else {
			return $this->fetch();
		}
	}
	//收款码付款
	public function cz_pay(){
	header('Access-Control-Allow-Origin:*');
		if (request()->isAjax()) {
			$price=input('money');
			$sn=order_create_no();
			$openid=session("openid");

			if(!session('user_info')){
				echo '充值失败';exit;
			}
			$this->add_log($sn,$price,4,0,0,0,0,0,0,0,0);
			import("payment.wxpay.WxPayApi");
			import("payment.wxpay.JsApiPay");
			$tools = new \JsApiPay();
			$input = new \WxPayUnifiedOrder();
			$input->SetBody('新零售商学院');
			$input->SetAttach('充值');
			$input->SetOut_trade_no($sn);
			$input->SetTotal_fee($price*100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'index/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openid);
		
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo $jsApiParameters;
			exit;
		} else {
			return $this->fetch();
		}
	}
	/**
	 *  type1 普通会员2企业会员3订单4充值5收款码收款6预定
	 *  
	 */
	private function add_log($sn,$price,$type,$tj_id,$pt_id,$tj_id2,$tj_yj,$tj_yj2,$pt_yj,$city_id=0,$city_yj=0){
		$user_id=session('user_info')['id'];	
		$data['sn']=$sn;
		$data['tj_id']=$tj_id;
		$data['tj_yj']=$tj_yj;
		$data['tj_id2']=$tj_id2;
		$data['tj_yj2']=$tj_yj2;
		$data['pt_id']=$pt_id;
		$data['pt_yj']=$pt_yj;
		$data['city_id']=$city_id;
		$data['city_yj']=$city_yj;
		$data['user_id'] = $user_id;
		$data['add_time'] = now_time();
		$data['order_type']=$type;
		$data['balance'] = $price;
		
		return db('paylog')->insert($data);
		
	}
	//红包发放记录
	public function send_hb($openId,$price,$title){
		import("payment.wxpay.WxPay");
		//①、获取当前访问页面的用户openid（如果给指定用户发送红包，则填写指定用户的openid)
		$wxPay = new \WxpayService();

		if(!$openId) exit('获取openid失败');
		//②、发送红包
		$outTradeNo = order_create_no();     //你自己的商品订单号
		$payAmount = $price;          //红包金额，单位:元
		$sendName = $title;    //红包发送者名称
		$wishing = '您的奖励红包！';      //红包祝福语
		$act_name='奖励红包';           //活动名称
		$result = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$sendName,$wishing,$act_name);
		file_put_contents("hb.txt", $result.PHP_EOL, FILE_APPEND);
		return true;
		//echo 'success';
	}
	
	//企业付款
	public function send_pay($openId,$outTradeNo,$price,$message){
	    import("payment.wxpay.Mpay");
	    $wxPay = new \WxRedpack();
	    //$oid="otx0ewIY-HKwa5p0gql3bDfp562A";
	    //$outTradeNo = order_create_no();
	    return $wxPay->mchpay($openId,$price,order_create_no(),$message);
	    
	}
	//企业付款
	public function send_pay1(){
	    import("payment.wxpay.Mpay");
	    $wxPay = new \WxRedpack();
	   $oid="oQq11sza3FIp10bRDq4iKF1g0iu4";
	    $outTradeNo = order_create_no();
	    $wxPay->mchpay($oid,1,$outTradeNo,'cs');
	    return true;
	    //echo 'success';
	}
	/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
	public function wechat() {
		header('Access-Control-Allow-Origin:*');
		if (request()->isAjax()) {
			import("payment.wxpay.WxPayApi");
			import("payment.wxpay.JsApiPay");
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input('body'));
			// 商品补充说明
			$input->SetAttach(input('attach'));
			// 商户订单号32位以下
			$input->SetOut_trade_no(input('out_trade_no'));
			// 价格，单位分
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'index/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid(session("openid"));
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo $jsApiParameters;
			exit;
		} else {
			return $this->fetch();
		}
	}
	
	public function lc_wechat() {
		header('Access-Control-Allow-Origin:*');
		if (request()->isPost()) {
			import("payment.wxpay.WxPayApi");
			import("payment.wxpay.JsApiPay");
			
			//获取当前用户信息
			$user_info = db('member')->where('id',session('user_id'))->find();
			
			$order_type =  input('order_type');
			
			if($order_type == 6){
				//获取预订信息
				$reserve_info = db('reserve')->where('order_sn',input('out_trade_no'))->find();
				$price=$reserve_info['balance'];
				if($reserve_info){
					//获取商品信息
					$beaut_home = db('beaut_home')->where('id',$reserve_info['home_id'])->find();
					
					$result = $this->add_log($reserve_info['order_sn'],$reserve_info['balance'],6,$user_info['pid1'],$user_info['pt_id'],
								$user_info['pid2'],$beaut_home['hy1_balance'],$beaut_home['hy2_balance'],$beaut_home['pt_balance'],$user_info['city_id'],$beaut_home['city_balance']);
					$out_trade_no = $reserve_info['order_sn'];
				}else{
					return json(['code'=>406,'msg'=>"付款失败"]);
				}
				if(!$result){
					return json(['code'=>405,'msg'=>"付款失败"]);
				}
			}else if($order_type == 3){
				$result = true;
				Db::startTrans();
				//获取订单信息
				$order_info = db('good_order')->where('order_id',input('order_id'))->find();
				$price=$order_info['pay_price'];
				if($order_info){
					//更新订单信息
					db('member')->where('id',session('user_id'))->update(['consignee'=>input('consignee'),'con_mobile'=>input('mobile'),'address'=>input('address')]);
					$rest1 = $this->update_order($order_info['order_id'],input('message'),input('consignee'),input('mobile'),input('address'));
					if(!$rest1) $result = false;
					
					$rest2 = $this->add_log($order_info['order_sn'],$order_info['pay_price'],3,$user_info['pid1'],$user_info['pt_id'],
								$user_info['pid2'],$order_info['tj_yj'],$order_info['tj_yj2'],$order_info['pt_yj'],$user_info['city_id'],$order_info['ct_yj']);
					if(!$rest2) $result = false;
					
					$out_trade_no = $order_info['order_sn'];
					
					if(!$result){
						Db::rollback();
						return json(['code'=>406,'msg'=>"付款失败"]);
					}else{
						Db::commit();
					}
				}else{
					return json(['code'=>405,'msg'=>"付款失败"]);
				}
			}
			
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input('body'));
			// 商品补充说明
			$input->SetAttach(input('attach'));
			// 商户订单号32位以下
			$input->SetOut_trade_no($out_trade_no);
			// 价格，单位分
			$input->SetTotal_fee($price*100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'index/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid(session("openid"));
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
		}
	}

	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		$notify->Handle(false);
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		//处理回调
		if($data['return_code'] == "SUCCESS"){
			//查找当前支付日志状态
			$sn=$data['out_trade_no'];
			file_put_contents("log.txt", now_time().$sn.PHP_EOL, FILE_APPEND);
			$ticket=db("paylog")->where("sn",$sn)->find();
			//判断当前是否支付完成
			if($ticket['state'] != 2){
				if($ticket['order_type']==1||$ticket['order_type']==2){
					$this->do_callback($ticket);
				}else if($ticket['order_type']==6){
					$this->callback_reserve($sn);
				}else if($ticket['order_type']==3){
					$this->callback_order($ticket);
				}else if($ticket['order_type']==4){
					$this->callback_cz($ticket);
				}
				
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}	
	}
	function test($sn){
		$log=db('paylog')->where('sn',$sn)->find();
		$this->do_callback($log, $log['user_id']);
	}
	function callback_cz($log){
		$user_id=$log['user_id'];
		$sn=$log['sn'];
		Db::startTrans();
		$result=true;
	    $res=db("paylog")->where("sn",$sn)->update(["state"=>2,"pay_time"=>now_time()]);
		if(!$res){
			$result=false;
		}
		$balance=$log['balance']*config('bili');
		member_charge_log($user_id,$log['balance'],'充值',4,$sn);
		$sql="update cz_member set money= money + ".$balance." where id=".$user_id ;
		$res=Db::execute($sql);
		if(!$res){
			$result=false;
		}
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
	}
	//开通普通会员和企业会员
	public function do_callback($log){
		$user_id=$log['user_id'];
		$type=$log['order_type'];
		$sn=$log['sn'];
		Db::startTrans();
		$result=true;
	    $res=db("paylog")->where("sn",$sn)->update(["state"=>2,"pay_time"=>now_time()]);
		if(!$res){
			$result=false;
		}
		$up['is_rz']=1;
		$config =get_config('ticket_config');
		$jlj=$config['m_send'];
		if($type==2){
			$up['is_qy']=1;
			$jlj=$config['qy_send'];
		}
		$up['total_xf']=["exp","total_xf+".$log['balance']];
		$res=db('member')->where('id',$user_id)->update($up);
		if(!$res){
			$result=false;
		}
		if($result){
			Db::commit();
			$res=$this->add_hbjl($user_id, $type, $jlj);
			if($res){
				$kt_user=db("member")->field("open_id")->where("id",$user_id)->find();
				$this->send_pay($kt_user['open_id'],'',$jlj,'创客奖励金每天发放');
			}
			if($log['tj_id']&&$log['tj_yj']){//直接推荐会员
				$pid1=db('member')->where('id',$log['tj_id'])->field("open_id,pt_id,city_id")->find();
				gdyj_record_log($log['tj_id'],$log['tj_yj'],"直接推荐创客奖励",6,$sn,$pid1['pt_id'],$pid1['city_id'],$user_id);
				$this->send_pay($pid1['open_id'],$sn,$log['tj_yj'],'直接推荐创客奖励');
			}
			if($log['tj_id2']&&$log['tj_yj2']){
				$pid2=db('member')->where('id',$log['tj_id2'])->field("open_id,pt_id,city_id")->find();
				gdyj_record_log($log['tj_id2'],$log['tj_yj2'],"间接推荐创客奖励",7,$sn,$pid2['pt_id'],$pid2['city_id'],$user_id);
				$this->send_pay($pid2['open_id'],$sn,$log['tj_yj2'],'间接推荐创客奖励');
			}
		
			if($log['pt_id']&&$log['pt_yj']){
				gdyj_record_log($log['pt_id'],$log['pt_yj'],"推荐创客合伙人奖励",8,$sn,$log['pt_id'],$log['city_id'],$user_id);
				$sql="update cz_member set total_yj= total_yj + ".$log['pt_yj'].",yj=yj+".$log['pt_yj']." where id=".$log['pt_id'] ;
				Db::execute($sql);
			}
			if($log['city_id']&&$log['city_yj']){
				gdyj_record_log($log['city_id'],$log['city_yj'],"推荐创客城市运营中心奖励",5,$sn,$log['pt_id'],$log['city_id'],$user_id);
				$sql="update cz_member set total_yj= total_yj + ".$log['city_yj'].",yj=yj+".$log['city_yj']." where id=".$log['city_id'] ;
				Db::execute($sql);
			}
			$this->send_mess();
		}else{
			Db::rollback();
		}
	}
	public function send_mess(){
			$data=array(
			 	"first" => array(
	                "value"=>'会员通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>'通过',
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>session('user_info')['id'],
					"color"=>"#173177"
				),
				
	            "remark"=> array(
	                "value"=>'付款成功,您已经是正式会员了',
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage(session('open_id'),config("tz1"),$data,config('DOMAIN')."index/member");	
	}
	public function add_hbjl($user_id,$type,$balance){
		$data['user_id']=$user_id;
		$data['type']=$type;
		$data['balance']=$balance;
		$data['message']='奖励金';
		$data['add_time']=now_time();
		$res=db("hb_list")->insert($data);
		return $res;
	}
	/**
	 * 注册会员
	 */
	function add_user($openid,$pid1,$pt_id,$pid2,$city_id){
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$res=file_get_contents($url);
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			$data['nick_name']=$array1['nickname'];
			$data['logo']=$array1['headimgurl'];
			$data['is_atten']=1;
		}
		$data['pid1']			= $pid1;
		$data['pid2']			= $pid2;
		$data['pt_id']			= $pt_id;
		$data['city_id']		=$city_id;
		$data['open_id']			= $openid;
		$data['add_time']		= now_time();
		$user_id=db('member')->insert($data);
		$user_info = db('member') -> where("open_id", $openid) -> find();
		session('user_info', $user_info);
	}
	
	//预定
	function  callback_reserve($order_sn){
		$pay_info = db('paylog')->where('sn',$order_sn)->find();
		$reserve_info = db('reserve')->where('order_sn',$order_sn)->find();
		$beaut_home = db('beaut_home')->where('id',$reserve_info['home_id'])->find();
		$pay_user_info = db('member')->where('id',$pay_info['user_id'])->find();
		$result = true;
		// 启动事务
		Db::startTrans();	
		//订房成功，跟新订房信息
		$rest1 = db('reserve')->where('order_sn',$order_sn)->update(['state'=>1]);
		if(!$rest1) $result =false;
		//更新付款用户的信息
		$rest2 = db('member')->where('id', $pay_info['user_id'])->setInc('total_xf', $pay_info['balance']);
		if(!$rest2) $result =false;

		//更新付款信息
		$rest9 = db('paylog')->where('sn',$order_sn)->update(['state'=>2]);
		if(!$rest9) $result =false;
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		
	}

	
	function callback_order($pay_info){
		//获取付款用户信息
		$pay_user_info = db('member')->where('id',$pay_info['user_id'])->find();
		//获取订单信息
		$order_info = db('good_order')->where('order_sn',$pay_info['sn'])->find();
		
		$result = true;
		// 启动事务
		Db::startTrans();	

		//更新订单信息
		$rest10 = db('good_order')->where('order_id',$order_info['order_id'])->update(['status'=>2,'pay_time'=>now_time()]);
		if(!$rest10) $result =false;
		//更新付款日志
		$rest11 = db('paylog')->where('id',$pay_info['id'])->update(['state'=>2,'pay_time'=>now_time()]);
		if(!$rest11) $result =false;
		
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
	}

	//更新订单
function update_order($order_id,$memo,$consignee,$mobile,$address){
	
	$order_info['consignee'] 	= $consignee;
	$order_info['address'] 		= $address;
	$order_info['mobile'] 		= $mobile;
	$order_info['memo'] 		= $memo;
	$order_info['pay_time'] 	= now_time();
	
	
	return db('good_order')->where('order_id', $order_id)->update($order_info);
}
	
	function test_pay_order(){
		$paylog_info = db('paylog')->where('sn',input('sn'))->find();
		$this->callback_order($paylog_info);
		
		
	}
}
